package com.hitqz.robot.biz.flow.component.agv;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hitqz.robot.api.business.model.dto.FlowContextDto;
import com.hitqz.robot.api.business.model.dto.FlowPatrolPreAndEndTicketsDto;
import com.hitqz.robot.api.common.entity.Tickets;
import com.hitqz.robot.api.common.entity.TicketsTask;
import com.hitqz.robot.biz.flow.domain.constant.FlowConstant;
import com.hitqz.robot.biz.flow.util.LiteFlowUtil;
import com.hitqz.robot.common.core.util.R;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @author xupkun
 * @date 2025/5/11
 */
@Slf4j
@LiteflowComponent(value = "AgvFindBestPlace", name = "[轮对/轮轴]查询缓存架最佳的位置")
@AllArgsConstructor
public class AgvFindBestPlace extends NodeComponent {

    private final RestTemplate restTemplate;

    private static final String url = "http://127.0.0.1:9999/admin/agv/goodsBufferFindPlacePut";

    private static final String notifyUri = "http://172.226.0.166:8090/api/v1/centrApp/agv/cfj/full";

    @Override
    public void process() throws Exception {
        LiteFlowUtil.checkInterruptFlag();
        FlowContextDto dto = this.getRequestData();
        TicketsTask task = dto.getTicketsTask();
        log.info("任务数据 {}", task.getParseOrderParams());
        FlowPatrolPreAndEndTicketsDto ticketsDto = JSONObject.parseObject(dto.getTicketsTask()
                .getParseOrderParams(), FlowPatrolPreAndEndTicketsDto.class);
        String source = Optional.ofNullable(ticketsDto.getModalData().get("sourcePosName"))
                .orElse(ticketsDto.getModalData().get("sourcePosCode")).toString();
        String targetName = Optional.ofNullable(ticketsDto.getModalData().get("targetPosName"))
                .orElse(ticketsDto.getModalData().get("targetPosCode")).toString();
        String srcnum = String.valueOf(ticketsDto.getModalData().get("srcnum"));
        String zx = String.valueOf(ticketsDto.getModalData().get("zx"));
        String srcPlace=String.valueOf(ticketsDto.getModalData().get("srcplace"));
        Tickets tickets = dto.getTickets();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf("application/json;UTF-8"));
        JSONObject requestParams = new JSONObject();
        requestParams.put("src", source);
        requestParams.put("dest", targetName);
        requestParams.put("num", srcnum);
        requestParams.put("zx", zx);
        requestParams.put("srcPlace",srcPlace);
        requestParams.put("storeData", JSONArray.parse(String.valueOf(ticketsDto.getModalData().get("pjData"))));
        HttpEntity<String> strEntity = new HttpEntity<String>(requestParams.toString(), headers);
        boolean notify = false;
        while (true) {
            try {
                log.info("\n===>request:{}", requestParams);
                String result = restTemplate.postForObject(url,
                        strEntity, String.class);
                JSONObject jsonObject = JSONObject.parseObject(result);
                log.info("\n===>result:{}", jsonObject);
                if (jsonObject.getInteger("code") == 0) {
                    JSONArray jsonArray = jsonObject.getJSONArray("data");
                    if (!jsonArray.isEmpty()) {
                        JSONObject jsonObject1 = (JSONObject) jsonArray.get(0);
                        String finalPlace = jsonObject1.getString("bindPosName");
                        log.info("finalPlace:" + finalPlace);
                        ticketsDto.getModalData().put("targetPosName", finalPlace);

                        JSONArray array = new JSONArray();
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject j = (JSONObject) jsonArray.get(i);
                            String d = j.getString("storeData");
                            if (StringUtils.hasText(d)) {
                                array.add(JSONObject.parseObject(d));
                            }
                        }
                        if (!array.isEmpty()) {
                            log.info("==>new pjData:{}",array.toJSONString());
                            ticketsDto.getModalData().put("pjData", array.toJSONString());
                        }

                        dto.getTicketsTask().setParseOrderParams(JSONObject.toJSONString(ticketsDto));
                        break;
                    } else {

                        TimeUnit.SECONDS.sleep(5);
                        if (!notify) {
                            notify = true;
                            HttpHeaders notifyHeader = new HttpHeaders();
                            headers.setContentType(MediaType.valueOf("application/json;UTF-8"));
                            jsonObject.put("taskCode", tickets.getTaskNo());
                            HttpEntity<String> notifyEntity = new HttpEntity<String>(jsonObject.toString(), notifyHeader);
                            log.info("{} 通知报警的AGV接口式:{}", notifyUri, notifyEntity);
                            String notifyResult = restTemplate.postForObject(notifyUri,
                                    strEntity, String.class);
                            log.info("返回结果" + notifyResult);
                        }
                    }

                } else {
                    log.info("报警并且等待完成");
                }
            } catch (Exception e) {
                log.info("发生异常:" + e.getMessage());
                TimeUnit.SECONDS.sleep(5);
            }

        }

    }
}
